# May 25, 2021

# This file creates the figures included in the manuscript and appendix
# It requires the following libraries: tidyverse (specifically dplyr, readr,
# stringr, purrr, and ggplot2), ggthemes, aod, binom, cowplot

############################################################
# PRELIMINARY
############################################################
source("loadPackages.R")
loadPackages(c("glue", "dplyr", "purrr", "readr", "stringr", 
               "ggplot2", "aod", "ggthemes", "binom", "cowplot",
               "tidyr"))

# The following function helps us calculate continuation values
# and maximum offers, which are necessary for (b)
source("cvFunctions.R")

# The following uses cvFunctions to find cont. values, etc.
# and then merges them with the experimental data
source("eqMerge.R")


# LOAD FILES

# Please ensure that the working directory is set to the replication folder
combined.df.full <- read_csv("EquilibriumExperimentCombined.csv")
equilibrium.full <- read_csv("EquilibriumValues.csv")
continuation.values <- read_csv("ContValueCalculations.csv")
QualitativeData <- read_csv("QualitativeData.csv")
ExperimentalData <- read_csv("ExperimentalData.csv")

# below we run the analysis without using the endogenous treatments
combined.df <- combined.df.full %>% filter(str_detect(treatment2, "RS", negate = TRUE))

equilibrium <- equilibrium.full %>% filter(str_detect(treatment2, "RS", negate = TRUE))


# To make qualitative figures in appendix, read in Qualitative Data


###############################################################
# MANUSCRIPT FIGURES
###############################################################

# MANUSCRIPT FIGURE 1
dat2 <- combined.df  %>%
  dplyr::select(-receiverDecision, -mover, -Player1, -Player2,  -matchId) %>% 
  dplyr::mutate(treatment2 = factor(treatment2, levels = c("BL", "CP", "VN", "CP-VN"))) %>% 
  dplyr::group_by(groupmatch) %>% 
  dplyr::mutate(averageOffer = mean(offer)) %>%
  dplyr::select(-offer) %>%
  dplyr::mutate(maxRound = max(roundId)) %>% 
  dplyr::select(-roundId) %>% 
  dplyr::distinct() %>%
  dplyr::ungroup() %>% dplyr::group_by(treatment2, maxRound) %>%
  dplyr::summarize(Observations = n(), Average = mean(averageOffer), SD = sd(averageOffer)) %>%
  dplyr::mutate(SE = SD/sqrt(Observations)) %>%
  dplyr::mutate(low_ci = Average - 1.96*SE, hi_ci = Average + 1.96*SE) %>%
  dplyr::mutate(across(c(low_ci, hi_ci), function(x) ifelse(x < 0, 0, x))) %>%
  dplyr::select(-SD, -SE) %>%
  dplyr::ungroup() %>% 
  dplyr::mutate(maxRound = maxRound + 1)


byRoundAll <- dat2 %>%
  ggplot(aes(x = maxRound, y = Average, group = treatment2)) + 
  geom_col(fill = "grey60", width = 0.8) +
  geom_errorbar(aes(ymin  =  low_ci, ymax  =  hi_ci),  size  =  0.3) +
  xlab("Match Length (in Rounds)") + ylab("Average Match Offer (across all Rounds)") +  
  facet_wrap(facets = vars(treatment2), nrow = 1) +
  theme_bw() + 
  geom_text(aes(x = maxRound, y = ifelse(is.na(hi_ci), Average + 3, hi_ci), 
                label = paste("n = ", round(Observations, 0)), angle = 60), size = 2, nudge_y = 6)


ggdraw(byRoundAll)

#ggsave("FIG_Average_Offer_Agreement.pdf",  plot = last_plot(),  device = "pdf",  width = 9, height = 7, units = "in")


# MANUSCRIPT FIGURE 2

prev_avg <- combined.df %>% 
  dplyr::select(groupmatch, roundId, offer, mover) %>%
  dplyr::group_by(groupmatch, mover) %>%
  dplyr::mutate(moveNumber = ifelse(mover == "Player1", 1 + (roundId/2), (roundId+1)/2)) %>%
  dplyr::ungroup() %>% select(-roundId) %>% 
  tidyr::pivot_wider(names_from = moveNumber, values_from = offer) %>%
  dplyr::rename(Move1 = `1`, Move2 = `2`, Move3 = `3`, Move4 = `4`) %>%
  dplyr::mutate(M2.Past.Avg = Move1,
                M3.Past.Avg = ifelse(is.na(Move2), NA, (Move1 + Move2)/2),
                M4.Past.Avg = ifelse(is.na(Move3), NA, (Move1 + Move2 + Move3)/3)) %>%
  dplyr::select(-Move1, -Move2, -Move3, -Move4) %>%
  tidyr::pivot_longer(names_to = "MoveType", values_to = "Past_Player_Match", cols = c(M2.Past.Avg:M4.Past.Avg)) %>%
  dplyr::mutate(MoveNumeric = str_extract(MoveType, "[1-4]"),
                MoveNumeric = as.numeric(MoveNumeric),
                roundId = ifelse(mover == "Player1",
                                 (MoveNumeric-1)*2,
                                 MoveNumeric*2 - 1)) %>%
  dplyr::select(-MoveType, -MoveNumeric, mover, groupmatch, Past_Player_Match) %>%
  dplyr::right_join(combined.df %>% 
                      dplyr::filter(roundId > 1)) %>%
  dplyr::group_by(roundId, treatment2) %>%
  dplyr::summarize(number_remaining = n(), 
                   mean_past_round_offers = mean(Past_Player_Match),
                   se = sd(Past_Player_Match)/sqrt(number_remaining),
                   upper_bound = mean_past_round_offers + 1.96 * se,
                   lower_bound = mean_past_round_offers - 1.96 * se) %>%
  dplyr::ungroup() %>%
  dplyr::mutate(Player = ifelse(roundId%%2 == 0, "Player A", "Player B"),
                Round = roundId + 1) %>%
  dplyr::select(-roundId) %>% dplyr::rename(Treatment = treatment2) %>% 
  ggplot(group = interaction(Player, Treatment)) + 
  geom_col(aes(x = Round, y = mean_past_round_offers), 
           position = position_dodge(), width = 0.8, fill = "grey60") + 
  geom_errorbar(size = 0.3, aes(x = Round, group = Treatment,  ymin = lower_bound,  ymax = upper_bound)) +
  xlab("Round") + 
  ylab("Offerer's Average Offers\nPrevious Rounds") +
  facet_grid(Player ~ Treatment) +
  theme_bw(base_size = 14) +
  theme(axis.title.y  =  element_text(size  =  rel(1.1)),
        axis.title = element_text(size = 12), 
        plot.title = element_text(size = 16),
        axis.title.x  =  element_text(size  =  rel(1.1)),
        strip.text.x = element_text(size = rel(1)),
        strip.text.y = element_text(size = rel(1))) +
  geom_text(aes(x = Round, y = upper_bound, 
                label = paste("n = ", round(number_remaining, 0)), angle = 60),
            size = 2, nudge_y = 9) + 
  scale_y_continuous(breaks = seq(from = 0, to = 80, by = 20)) 

ggdraw(prev_avg)

#ggsave("FIG_Average_Offer_Previous.pdf",  plot = last_plot(),  device = "pdf",  width = 9, height = 6, units = "in")


# MANUSCRIPT FIGURE 3

cumulative.plot.df.1 <-  combined.df %>% group_by(treatment2) %>% 
  do(orig_vals = .[.$roundId == 0,],
     accepted_0 = .[(.$roundId <= 0 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_1 = .[(.$roundId <= 1 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_2 = .[(.$roundId <= 2 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_3 = .[(.$roundId <= 3 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_4 = .[(.$roundId <= 4 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_5 = .[(.$roundId <= 5 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_6 = .[(.$roundId <= 6 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_7 = .[(.$roundId <= 7 & (.$receiverDecision == "ACCEPT")), ],
     rD.df = min(.$roundId[.$eq_rD == "ACCEPT"])) %>%
  mutate_at(vars(orig_vals, accepted_0, accepted_1, accepted_2, accepted_3, 
                 accepted_4, accepted_5, accepted_6, accepted_7),
            funs(as.data.frame(.) %>% nrow())) %>%
  mutate(rD.df = as.numeric(as.data.frame(rD.df))) %>%
  gather(Variable_Name, Number, accepted_0:accepted_7) %>% 
  dplyr::rename(Original_Number_Pairs = orig_vals, eqRound = rD.df) %>% 
  mutate(Variable_Name = gsub("[^\\d]+", "", Variable_Name, perl = TRUE)) %>% 
  dplyr::rename(roundId = Variable_Name, Treatment = treatment2) %>% 
  mutate(roundId = as.numeric(roundId), eqRound = as.numeric(eqRound)) 

cumulative.plot.df.2 <- cumulative.plot.df.1 %>% arrange(Treatment, roundId) %>% group_by(Treatment) %>%
  mutate(previousTotal = ifelse(roundId == 0, 0, lag(Number))) %>%
  mutate(inRound = Number - previousTotal) %>% ungroup() %>% split(.$Treatment) %>%
  map(function(x){
    z <- x %>% rbind(slice(x, 8) %>% mutate(roundId = 8,  Number = Original_Number_Pairs)) %>%
      mutate(previousTotal = ifelse(roundId == 8,  lag(Number), previousTotal))%>% 
      mutate(inRound = ifelse(roundId == 8,  Number - previousTotal, inRound))
  }) %>% bind_rows() %>% mutate(inRound = inRound/Original_Number_Pairs, 
                                Number = Number/Original_Number_Pairs) %>% 
  select(Treatment, roundId, x = Number)

cumulative.plot.df <- combined.df %>% group_by(treatment2) %>% 
  do(orig_vals = .[.$roundId == 0,],
     accepted_0 = .[(.$roundId <= 0 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_1 = .[(.$roundId <= 1 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_2 = .[(.$roundId <= 2 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_3 = .[(.$roundId <= 3 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_4 = .[(.$roundId <= 4 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_5 = .[(.$roundId <= 5 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_6 = .[(.$roundId <= 6 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_7 = .[(.$roundId <= 7 & (.$receiverDecision == "ACCEPT")), ],
     rD.df = min(.$roundId[.$eq_rD == "ACCEPT"])) %>%
  mutate_at(vars(orig_vals, accepted_0, accepted_1, accepted_2, accepted_3, 
                 accepted_4, accepted_5, accepted_6, accepted_7),
            funs(as.data.frame(.) %>% nrow())) %>%
  mutate(rD.df = as.numeric(as.data.frame(rD.df))) %>%
  gather(Variable_Name, Number, accepted_0:accepted_7) %>% 
  dplyr::rename(Original_Number_Pairs = orig_vals, eqRound = rD.df) %>% 
  mutate(Variable_Name = gsub("[^\\d]+", "", Variable_Name, perl = TRUE)) %>% 
  dplyr::rename(roundId = Variable_Name, Treatment = treatment2) %>% 
  mutate(roundId = as.numeric(roundId), eqRound = as.numeric(eqRound)) %>%
  group_by(Treatment, roundId) %>% 
  mutate(Lower_Bound = binom.confint(Number, Original_Number_Pairs, methods="exact")$lower,
         Upper_Bound = binom.confint(Number, Original_Number_Pairs, methods="exact")$upper,
         Mean = binom.confint(Number, Original_Number_Pairs, methods="exact")$mean) %>%
  select(-Original_Number_Pairs, -Number) %>% ungroup() %>%
  mutate(Treatment = factor(Treatment, levels = c("BL", "CP", "VN", "CP-VN"))) %>%
  mutate(eqRound = ifelse(eqRound == roundId, 1, 0))


pd = position_dodge(0.3)
shape.values = c(16, 1, 0, 15)
line.values = c("solid", "dashed", "dotdash", "dotted")

fig.cumulative.plot <- cumulative.plot.df %>% 
  ggplot(aes(x = roundId+1, y = Mean, group = Treatment, eqRound))  +  
  geom_point(aes(shape = Treatment, size = factor(eqRound)),  position = pd) + 
  scale_shape_manual(name  =  "Treatment", values = shape.values) + 
  geom_line(aes(linetype = factor(Treatment)), size = 0.2, 
            position = pd) + 
  geom_errorbar(width = .1, size = 0.3, 
                position = pd, 
                aes(ymin=Lower_Bound, ymax = Upper_Bound)) + 
  xlab("Round") + ylab("Cumulative Proportion Accepted") +  
  scale_y_continuous(breaks = seq(from = 0,to = 2,by = .1)) +  
  scale_x_continuous(breaks = seq(from = 1,to = 8,by = 1)) + 
  scale_linetype_manual(name  =  "Treatment", values = line.values) + 
  scale_size_manual(guide = "none", values  =  c(2, 3.5)) + 
  guides(shape  =  guide_legend(nrow  =  2)) + theme_bw(base_size = 14) + 
  theme(legend.position = "bottom", legend.text = element_text(size = 12),
        axis.title = element_text(size = 12), 
        plot.title = element_text(size = 16)) + 
  coord_cartesian(ylim  =  c(0.1, 0.7)) + 
  theme(axis.title.y  =  element_text(size  =  rel(1.5), angle  =  90)) + 
  theme(axis.title.x  =  element_text(size  =  rel(1.5))) + 
  theme(plot.title  =  element_text(size  =  rel(1.75))) + 
  theme(legend.text = element_text(size = rel(1)),
        legend.title = element_text(size = rel(1))) +
  annotate("text", x = 6.5, y = 0.2, 
           label = "Larger points: 100% acceptance in equilibrium",
           size = 4) + theme_bw(base_family = "Gill Sans MT", base_size = 14) +  
  theme(axis.line = element_line(color = 'black'), axis.title.x = element_text(vjust = -0.3),  
        axis.title.y = element_text(vjust = 0.8), legend.background = element_blank(),  
        legend.key = element_blank(),  legend.title = element_text(face="plain"), 
        panel.background = element_blank(),  panel.border = element_blank(), 
        panel.grid = element_blank(), plot.background = element_blank(), 
        strip.background = element_blank()) + theme_bw(base_size = 14)



ggdraw(fig.cumulative.plot)
#ggsave("FIG_Cumulative_Offer_Acceptance.pdf",  plot = last_plot(),  device = "pdf",  width = 9, height = 7, units = "in")



# MANUSCRIPT FIGURE 4

shape.values = c(16, 1, 0, 15)
line.values = c("solid", "dashed", "dotdash", "dotted")


mean.plot.df_diff <- combined.df %>%
  mutate(min.accept = ifelse(treatment2 == "BL"| treatment2 == "CP", 3, 5)) %>% 
  group_by(treatment2, roundId = roundId+1) %>% 
  dplyr::summarise(mean_offer = mean(offer_diff), 
                   sd_offer = sd(offer_diff), 
                   number_offer = n(), 
                   se_offer = sd_offer/sqrt(number_offer), 
                   min.val = mean(min.accept)) %>% 
  ungroup() %>% 
  mutate(first_accept = ifelse(min.val == roundId, 1, 0), 
         low_ci = mean_offer - 1.96*se_offer, 
         hi_ci =  mean_offer + 1.96*se_offer) %>% 
  select(-number_offer, -se_offer, - sd_offer) %>% 
  as.data.frame() %>% 
  mutate(Player = ifelse(roundId%%2 == 1, "Player A", "Player B"),
         treatment2 = factor(treatment2, levels = rev(c("BL", "CP", "VN", "CP-VN"))))


fig.mean.plot.diff <-  mean.plot.df_diff %>% 
  filter(roundId == 1|roundId==2) %>%
  ggplot(aes(x = mean_offer, y = treatment2, group = treatment2)) + 
  geom_vline(xintercept = 0, linetype = "dotted", size = 0.2) +
  geom_point(position  =  position_dodge(0.3), aes(shape = treatment2), size = 3) + 
  scale_shape_manual(name  =  "Treatment", values  =  rev(shape.values)) + 
  facet_grid(~Player) + geom_errorbarh(height  =  .1, 
                                       size  =  0.3, aes(xmin  =  low_ci, xmax  =  hi_ci))  + 
  coord_cartesian(xlim  =  c(-15,30)) + 
  theme(legend.text  =  element_text(size  =  rel(1)),
        legend.title  =  element_text(size  =  rel(1))) + 
  xlab("First Offer Difference from Equilibrium Offer") + ylab("Treatment") +  
  theme_bw() +
  scale_x_continuous(breaks = seq(from  =  -20, to  =  30, by  =  10)) +  
  theme(axis.line = element_line(color = 'black'),
        #strip.background = element_rect(fill = "grey"),
        strip.text = element_text(size = rel(1.2)),
        axis.title.x = element_text(vjust = -0.3, size = rel(1.5)),  
        axis.title.y = element_text(vjust = 0.8, size  =  rel(1.5)), 
        #legend.text  =  element_text(size  =  rel(1)),  
        #legend.title  =  element_text(size  =  rel(1)), 
        #panel.background = element_blank(),  
        panel.border = element_blank(), 
        panel.grid = element_blank(), 
        plot.background = element_blank(), 
        legend.position="none")


ggdraw(fig.mean.plot.diff)
#ggsave("FIG_First_Offer_Diff_Eq.pdf",  plot = last_plot(),  device = "pdf",  width = 9, height = 4, units = "in")




# MANUSCRIPT FIGURE 5
pd = position_dodge(1)

fig.mean.plot.diff.by.round = mean.plot.df_diff %>% as_tibble() %>%
  mutate(treatment2 = factor(treatment2, levels = c("BL", "CP", "VN", "CP-VN"))) %>%
  ggplot(aes(x  =  roundId, y  =  mean_offer, group = treatment2)) + 
  geom_point(position  =  pd, 
             aes(shape  =  factor(treatment2), 
                 colour  =  factor(first_accept),
                 size  =  factor(first_accept))) + 
  geom_line(aes(linetype  =  factor(treatment2)), position = pd) + 
  geom_errorbar(width  =  .1, position  =  pd, 
                size  =  0.3, 
                aes(ymin  =  low_ci, 
                    ymax  =  hi_ci)) + 
  xlab("Round") + ylab("Difference from Equilibrium Offer") +  
  scale_y_continuous(breaks = seq(from = -70,to = 50,by = 10)) +  
  scale_x_continuous(breaks = seq(from  =  1, to  =  8, by  =  1)) +  
  scale_shape_manual(name = "Treatment",values  =  shape.values)  +  
  scale_linetype_manual(name="Treatment",values = line.values) +
  guides(shape  =  guide_legend(nrow  =  2)) +
  theme(legend.position = "bottom", 
        legend.text = element_text(size = 12), 
        axis.title = element_text(size = 12), 
        plot.title = element_text(size = 16)) +
  coord_cartesian(ylim  =  c(-70,50)) + 
  theme_bw(base_size = 14) +
  scale_colour_manual(guide  =  "none", values  =  c("black", "gray69"))  +  
  scale_size_manual(guide  =  "none", values   =   c(2, 3.5)) +
  theme(axis.title.y  =  element_text(size  =  rel(1.3))) + 
  theme(axis.title.x  =  element_text(size  =  rel(1.3))) + 
  #theme(plot.title  =  element_text(size  =  rel(1.75))) + 
  theme(legend.text  =  element_text(size  =  rel(1)),
        legend.title  =  element_text(size  =  rel(1)),
        strip.text = element_text(size = rel(1))) + 
  facet_wrap(~Player, scales  =  'free_x') + theme(panel.spacing = unit(2, "lines")) 



ggdraw(fig.mean.plot.diff.by.round)
#ggsave("FIG_Diff_Eq_by_Round.pdf",  plot = last_plot(),  device = "pdf",  width = 9, height = 7, units = "in")


# MANUSCRIPT FIGURE 6


# format equilibrium values in a similar fashion as the datasets
equilibrium.values.formatted <-  continuation.values %>%  
  mutate(roundId = Rounds - 1) %>%   
  select(treatment2 = Name, roundId, MaxCost.O, MaxCost.R) 


combined.df.maximum.cost <- combined.df.full %>% 
  left_join(equilibrium.values.formatted) %>% 
  mutate(Cost.R = 100 - offer) %>%
  mutate(should_accept = ifelse(Cost.R < MaxCost.R, 1, 0))




# Note that MaxCost.R is the maximum cost that the player should be willing to bear
# given continuation values. Cost.R is the implicit cost based on the offer.

combined.df.mc.dist = combined.df.maximum.cost %>% 
  filter(!(str_detect(treatment2, "^RS"))) %>%
  dplyr::rename(Treatment = treatment2, Round = roundId) %>%
  mutate(receiverDecision = ifelse(receiverDecision == "ACCEPT", 1, 0)) %>%
  mutate(Endow.R = case_when((str_detect(Treatment, "CP") == TRUE) & (Round%%2 == 0)~ 50,
                             (str_detect(Treatment, "CP") == TRUE) & (Round%%2 == 1) ~ 150,
                             TRUE ~ 100),
         Net_EU_Diff = MaxCost.R- Cost.R) %>%
  mutate(Treatment = factor(Treatment, levels = c("BL","CP", "VN", "CP-VN"))) %>% 
  ungroup() %>%
  mutate(Round = Round + 1) %>%
  mutate(Player = ifelse(Round%%2 == 1, "Offerer: Player A", "Offerer: Player B")) %>%
  mutate(Player_Number = ifelse(Round%%2 == 1, (Round + 1)/2, Round/2)) %>%
  select(-matchId, -Player1, -Player2, -groupmatch) %>%
  mutate(Round = ifelse(receiverDecision == 1, 2*Round - 1, 2*Round)) %>%
  mutate(Treatment = factor(Treatment, levels = c("BL", "CP-VN", "CP", "VN"))) %>%
  mutate(receiverDecision = ifelse(receiverDecision == 1, "Accept", "Reject")) %>%
  group_by(Round, Treatment, mover, Net_EU_Diff) %>% 
  dplyr::mutate(total = n()) %>%
  dplyr::mutate(num_assign = case_when(total == 1 ~ rep(0, n()), 
                                       TRUE ~ runif(n(), -1/2, 1/2))) %>%
  ungroup() %>%
  mutate(Net_EU_Diff_2 = Net_EU_Diff + num_assign,
         receiverDecision = factor(receiverDecision, levels = c("Accept", "Reject")),
         Treatment = factor(Treatment, levels = c("BL", "CP", "VN", "CP-VN")))







fig.dist.accepted.rejected <- combined.df.mc.dist %>%
  ggplot(aes(x = Round, y = Net_EU_Diff_2, 
             colour = receiverDecision,
             shape = receiverDecision)) + 
  geom_jitter(width = 0.3, size = 1.2, alpha = 0.5) +
  scale_x_continuous(breaks = seq(from = 1.6, to = 16.5, by = 2), labels = seq(from = 1, to = 8, by = 1)) + 
  xlab("Round") + ylab("Net Offer - CV") + 
  scale_y_continuous(breaks = seq(from = -100, to = 60, by = 50)) + 
  geom_hline(yintercept = 0, linetype = "dashed", size = .3) +
  facet_grid(Player ~ Treatment) + 
  labs(colour = "Receiver decision")  +  
  scale_shape_manual(name  =  "Receiver decision", values = c(16, 4)) + 
  scale_colour_grey(start = 0.1, end = 0.4) + 
  theme(legend.position="bottom", 
        legend.text=element_text(size=12), 
        axis.title=element_text(size=12), 
        plot.title=element_text(size=16)) +
  coord_cartesian(ylim = c(-105, 60)) + 
  theme_bw() +
  theme(axis.title.y = element_text(size = rel(1.3), vjust = 0.8), 
        axis.title.x = element_text(size = rel(1.3), vjust = -0.3),
        strip.text.x = element_text(size = rel(1.3)), 
        strip.text.y = element_text(size = rel(1.3)),
        plot.title = element_text(size = 16),  
        legend.text = element_text(size = rel(1), face = "plain"), 
        legend.title = element_text(size = rel(1), face = "plain"),
        axis.line = element_line(color = 'black'), 
        legend.background = element_blank(),  
        legend.key = element_blank(),  
        panel.background = element_blank(),  
        panel.border = element_blank(), 
        panel.grid = element_blank(), 
        plot.background = element_blank(), 
        legend.position="bottom", 
        #strip.background = element_blank()
  ) +  guides(colour = guide_legend(override.aes = list(size=2, alpha = 1))) 



ggdraw(fig.dist.accepted.rejected)
#ggsave("FIG_Dist_Accepted_Rejected.pdf",  plot = last_plot(),  device = pdf, width = 9, height = 6, units = "in")


###############################################################
# APPENDIX FIGURES (ANALYSIS)
###############################################################

# APPENDIX FIGURE 6

# Add a variable indicating where RS or RS-VN endowments were both 100

combined.df.full.formatted <- combined.df.full %>%  
  mutate(include_in_rs_subsetted = case_when(!(treatment2 %in% c("RS", "RS-VN")) ~ 1,  
                                             (i1 == 100 & i2 == 100) ~ 1,  
                                             TRUE ~ 0))


# Name the groups by which we divide observations
endog_endow = c("BL", "RS", "RS-VN")
uneven_tr = c("BL", "RS-VN", "CP-VN", "VN")

cumulative.plot.df.rs = combined.df.full.formatted %>% 
  group_by(treatment2, include_in_rs_subsetted) %>% 
  do(orig_vals = .[.$roundId == 0,],
     accepted_0 = .[(.$roundId <= 0 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_1 = .[(.$roundId <= 1 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_2 = .[(.$roundId <= 2 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_3 = .[(.$roundId <= 3 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_4 = .[(.$roundId <= 4 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_5 = .[(.$roundId <= 5 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_6 = .[(.$roundId <= 6 & (.$receiverDecision == "ACCEPT")), ], 
     accepted_7 = .[(.$roundId <= 7 & (.$receiverDecision == "ACCEPT")), ],
     rD.df = min(.$roundId[.$eq_rD == "ACCEPT"])) %>%
  mutate_at(vars(orig_vals, accepted_0, accepted_1, accepted_2, accepted_3, 
                 accepted_4, accepted_5, accepted_6, accepted_7),
            funs(as.data.frame(.) %>% nrow())) %>%
  mutate(rD.df = as.numeric(as.data.frame(rD.df))) %>%
  gather(Variable_Name, Number, accepted_0:accepted_7) %>% 
  dplyr::rename(Original_Number_Pairs = orig_vals, eqRound = rD.df) %>% 
  mutate(Variable_Name = gsub("[^\\d]+", "", Variable_Name, perl = TRUE)) %>% 
  dplyr::rename(roundId = Variable_Name, Treatment = treatment2) %>% 
  mutate(roundId = as.numeric(roundId), eqRound = as.numeric(eqRound)) %>%
  group_by(Treatment, roundId) %>% 
  mutate(Lower_Bound = binom.confint(Number, Original_Number_Pairs, methods="exact")$lower,
         Upper_Bound = binom.confint(Number, Original_Number_Pairs, methods="exact")$upper,
         Mean = binom.confint(Number, Original_Number_Pairs, methods="exact")$mean) %>%
  select(-Original_Number_Pairs, -Number) %>% ungroup() %>% 
  mutate(Treatment = factor(Treatment, levels = c("BL", "CP", "VN", "CP-VN", "RS", "RS-VN"))) %>% 
  mutate(eqRound = ifelse(eqRound == roundId, 1, 0)) %>% 
  mutate(endog_endow = ifelse(Treatment %in% endog_endow, 1, 0)) %>% 
  mutate(uneven_tr = ifelse(Treatment %in% uneven_tr, 1, 0)) 

# BL: 16, solid 
# CP: 1, dashed
# VN: 0, dotdash
# CP-VN: 15, dotted
# RS: 17, solid
# RS-VN: 2, dotdash

shape.values = c(16, 1, 0, 15, 17, 2)
names(shape.values) <- c("BL", "CP", "VN", "CP-VN", "RS", "RS-VN")
line.values = c("solid", "dashed", "dotdash", "dotted", "solid", "dotdash")
names(line.values) <- c("BL", "CP", "VN", "CP-VN", "RS", "RS-VN")
 

# APPENDIX FIGURE 6A: Uneven probability treatment subsetted
fig.cumulative.acceptances.vulnerability <- cumulative.plot.df.rs %>% filter(uneven_tr == 1) %>% 
  #mutate(eqRound = replace_na(eqRound, 0)) %>%
  mutate(eqRound = factor(eqRound),
         Treatment = factor(Treatment, levels = c("BL", "VN", "CP-VN", "RS-VN"))) %>%
  ggplot(aes(x = roundId+1, y = Mean, group = Treatment, eqRound))  + 
  geom_point(aes(shape = Treatment, size = factor(eqRound)), position = position_dodge(width = 0.8)) +  
  geom_line(aes(linetype = factor(Treatment)), size = 0.2,  position = position_dodge(width = 0.8)) + 
  geom_errorbar(width = .1, size = 0.3,  position = position_dodge(width = .8),  aes(ymin=Lower_Bound, ymax = Upper_Bound)) + 
  xlab("Round") + ylab("Cumulative Proportion Accepted") +  
  scale_y_continuous(breaks = seq(from = 0,to = 2,by = .1)) +  
  scale_x_continuous(breaks = seq(from = 1,to = 8,by = 1)) + 
  scale_linetype_manual(name  =  "Treatment", values = line.values[names(line.values) %in% uneven_tr]) + 
  scale_shape_manual(name  =  "Treatment", values = shape.values[names(shape.values) %in% uneven_tr]) + 
  scale_size_manual(guide = "none", values  =  c(2, 3.5)) + 
  guides(shape  =  guide_legend(nrow  =  2)) + theme_bw(base_size = 14) + 
  theme(legend.position = "bottom", legend.text = element_text(size = 12),
        axis.title = element_text(size = 12), 
        plot.title = element_text(size = 16)) + 
  coord_cartesian(ylim  =  c(0.1, 0.7)) + 
  theme(axis.title.y  =  element_text(size  =  rel(1.5), angle  =  90)) + 
  theme(axis.title.x  =  element_text(size  =  rel(1.5))) + 
  theme(plot.title  =  element_text(size  =  rel(1.75))) + 
  theme(legend.text = element_text(size = rel(1)),
        legend.title = element_text(size = rel(1))) +
  annotate("text", x = 6.5, y = 0.2, 
           label = "Larger points: 100% acceptance in equilibrium",
           size = 4) + theme_bw(base_size = 14) +  
  theme(axis.line = element_line(color = 'black'), axis.title.x = element_text(vjust = -0.3),  
        axis.title.y = element_text(vjust = 0.8), legend.background = element_blank(),  
        legend.key = element_blank(),  legend.title = element_text(face="plain"), 
        panel.background = element_blank(),  panel.border = element_blank(), 
        panel.grid = element_blank(), plot.background = element_blank(), 
        strip.background = element_blank()) + theme_bw(base_size = 14)

# APPENDIX FIGURE 6B: Endogenous selection subsetted
fig.cumulative.acceptances.endogenous <- cumulative.plot.df.rs %>% filter(endog_endow == 1) %>%  
  mutate(eqRound = replace_na(eqRound, 0)) %>%  
  mutate(eqRound = factor(eqRound), Treatment = factor(Treatment, levels = c("BL", "RS", "RS-VN"))) %>%  
  ggplot(aes(x = roundId+1, y = Mean, group = Treatment, eqRound))  + 
  geom_point(aes(shape = Treatment, size = factor(eqRound)), position = position_dodge(width = 0.8)) +  
  geom_point(aes(shape = factor(Treatment), size = factor(eqRound)), 
             position = position_dodge(width = 0.8)) +  
  geom_line(aes(linetype = factor(Treatment)), size = 0.2,  position = position_dodge(width = 0.8)) + 
  geom_errorbar(width = .1, size = 0.3,  position = position_dodge(width = .8),  aes(ymin=Lower_Bound, ymax = Upper_Bound)) + 
  xlab("Round") + ylab("Cumulative Proportion Accepted") +  
  scale_y_continuous(breaks = seq(from = 0,to = 2,by = .1)) +  
  scale_x_continuous(breaks = seq(from = 1,to = 8,by = 1)) + 
  scale_linetype_manual(name  =  "Treatment", values = line.values[names(line.values) %in% endog_endow]) + 
  scale_shape_manual(name  =  "Treatment", values = shape.values[names(line.values) %in% endog_endow]) + 
  scale_size_manual(guide = "none", values  =  c(2, 3.5)) + 
  guides(shape  =  guide_legend(nrow  =  2)) + theme_bw(base_size = 14) + 
  theme(legend.position = "bottom", legend.text = element_text(size = 12),
        axis.title = element_text(size = 12), 
        plot.title = element_text(size = 16)) + 
  coord_cartesian(ylim  =  c(0.1, 0.7)) + 
  theme(axis.title.y  =  element_text(size  =  rel(1.5), angle  =  90)) + 
  theme(axis.title.x  =  element_text(size  =  rel(1.5))) + 
  theme(plot.title  =  element_text(size  =  rel(1.75))) + 
  theme(legend.text = element_text(size = rel(1)),
        legend.title = element_text(size = rel(1))) +
  annotate("text", x = 6.5, y = 0.2, 
           label = "Larger points: 100% acceptance in equilibrium",
           size = 4) + theme_bw(base_size = 14) +  
  theme(axis.line = element_line(color = 'black'), axis.title.x = element_text(vjust = -0.3),  
        axis.title.y = element_text(vjust = 0.8), legend.background = element_blank(),  
        legend.key = element_blank(),  legend.title = element_text(face="plain"), 
        panel.background = element_blank(),  panel.border = element_blank(), 
        panel.grid = element_blank(), plot.background = element_blank(), 
        strip.background = element_blank()) 

ggdraw(fig.cumulative.acceptances.vulnerability)
#ggsave("FIG_APP_Cumulative_Vulnerability.pdf",  plot = last_plot(),  device = "pdf",  width = 7, height = 5, units = "in")


ggdraw(fig.cumulative.acceptances.endogenous)
#ggsave("FIG_APP_Cumulative_Endogenous.pdf",  plot = last_plot(),  device = "pdf",  width = 7, height = 5, units = "in")

# APPENDIX FIGURE 7

mean.plot.df_diff.rs <- combined.df.full.formatted %>% 
  mutate(min.accept = ifelse(treatment2 == "BL"| treatment2 == "BL"| treatment2 == "CP", 3, 5)) %>% 
  group_by(treatment2, roundId = roundId+1) %>% 
  dplyr::summarise(mean_offer = mean(offer_diff, na.rm = TRUE),  sd_offer = sd(offer_diff, na.rm = TRUE),  
                   number_offer = n(),  se_offer = sd_offer/sqrt(number_offer),  
                   min.val = mean(min.accept, na.rm = TRUE)) %>% 
  ungroup() %>% 
  mutate(first_accept = ifelse(min.val == roundId, 1, 0), 
         low_ci = mean_offer - 1.96*se_offer, 
         hi_ci =  mean_offer + 1.96*se_offer) %>% 
  select(-number_offer, -se_offer, - sd_offer) %>% 
  as.data.frame() %>% 
  mutate(Player = ifelse(roundId%%2 == 1, "Player A", "Player B"),
         treatment2 = factor(treatment2, levels = rev(c("BL", "CP", "VN", "CP-VN", "RS", "RS-VN"))))

fig.mean.plot.diff.rs = mean.plot.df_diff.rs %>% 
  filter(roundId == 1|roundId==2) %>%
  ggplot(aes(x = mean_offer, y = treatment2, group = treatment2)) + 
  geom_vline(xintercept = 0, linetype = "dotted", size = 0.2) +
  geom_point(position  =  position_dodge(0.3), aes(shape = treatment2), size = 3) + 
  scale_shape_manual(name  =  "Treatment", values  =  rev(shape.values)) + 
  facet_grid(~Player) + geom_errorbarh(height  =  .1, 
                                       size  =  0.3, aes(xmin  =  low_ci, xmax  =  hi_ci))  + 
  coord_cartesian(xlim  =  c(-15,30)) + 
  theme(axis.title.y  =  element_text(size  =  rel(1.5))) + 
  theme(axis.title.x  =  element_text(size  =  rel(1.5))) + 
  theme(legend.text  =  element_text(size  =  rel(1)),
        legend.title  =  element_text(size  =  rel(1))) + 
  xlab("First Offer Difference from Equilibrium Offer") + ylab("Treatment") + 
  theme_bw() +
  scale_x_continuous(breaks = seq(from  =  -20, to  =  30, by  =  10)) +  
  theme(axis.line = element_line(color = 'black'),
        #strip.background = element_rect(fill = "grey"),
        strip.text = element_text(size = rel(1.2)),
        axis.title.x = element_text(vjust = -0.3, size = rel(1.2)),  
        axis.title.y = element_text(size  =  rel(1.2)), 
        panel.border = element_blank(), 
        panel.grid = element_blank(), 
        plot.background = element_blank(), 
        legend.position="none")

ggdraw(fig.mean.plot.diff.rs)
#ggsave("FIG_APP_First_Offer_Diff_Eq.pdf",  plot = last_plot(),  device = "pdf",  width = 9, height = 4, units = "in")


# APPENDIX FIGURE 8
# FIGURE 8A

fig.mean.plot.diff.by.round.vulnerability <- mean.plot.df_diff.rs %>% 
  filter(treatment2 %in% uneven_tr) %>% as_tibble() %>%
  mutate(treatment2 = factor(treatment2, levels = c("BL", "VN", "CP-VN", "RS-VN"))) %>%
  ggplot(aes(x  =  roundId, y  =  mean_offer, group = treatment2)) + 
  geom_point(position  =  pd, 
             aes(shape  =  factor(treatment2), 
                 colour  =  factor(first_accept),
                 size  =  factor(first_accept))) + 
  geom_line(aes(linetype  =  factor(treatment2)), position = pd) + 
  geom_errorbar(width  =  .1, position  =  pd, 
                size  =  0.3, 
                aes(ymin  =  low_ci, 
                    ymax  =  hi_ci)) + 
  xlab("Round") + ylab("Difference from Equilibrium Offer") +  
  scale_y_continuous(breaks = seq(from = -70,to = 50,by = 10)) +  
  scale_x_continuous(breaks = seq(from  =  1, to  =  8, by  =  1)) +  
  scale_shape_manual(name = "Treatment",values  =  shape.values[names(shape.values) %in% uneven_tr])  +  
  scale_linetype_manual(name="Treatment",values = line.values[names(shape.values) %in% uneven_tr]) +
  guides(shape  =  guide_legend(nrow  =  2)) +
  theme(legend.position = "bottom", 
        legend.text = element_text(size = 12), 
        axis.title = element_text(size = 12), 
        plot.title = element_text(size = 16)) +
  coord_cartesian(ylim  =  c(-70,50)) + 
  theme_bw(base_size = 14) +
  scale_colour_manual(guide  =  "none", values  =  c("black", "gray69"))  +  
  scale_size_manual(guide  =  "none", values   =   c(2, 3.5)) +
  theme(axis.title.y  =  element_text(size  =  rel(1.2))) + 
  theme(axis.title.x  =  element_text(size  =  rel(1.2))) + 
  #theme(plot.title  =  element_text(size  =  rel(1.75))) + 
  theme(legend.text  =  element_text(size  =  rel(1)),
        legend.title  =  element_text(size  =  rel(1)),
        strip.text = element_text(size = rel(1))) + 
  facet_wrap(~Player, scales  =  'free_x') + 
  theme(legend.position = "bottom", panel.spacing = unit(2, "lines")) 



# FIGURE 8B

fig.mean.plot.diff.by.round.endogenous = mean.plot.df_diff.rs %>% 
  filter(treatment2 %in% endog_endow) %>% as_tibble() %>%
  mutate(treatment2 = factor(treatment2, levels = c("BL", "RS", "RS-VN"))) %>%
  ggplot(aes(x  =  roundId, y  =  mean_offer, group = treatment2)) + 
  geom_point(position  =  pd, 
             aes(shape  =  factor(treatment2), 
                 colour  =  factor(first_accept),
                 size  =  factor(first_accept))) + 
  geom_line(aes(linetype  =  factor(treatment2)), position = pd) + 
  geom_errorbar(width  =  .1, position  =  pd, 
                size  =  0.3, 
                aes(ymin  =  low_ci, 
                    ymax  =  hi_ci)) + 
  xlab("Round") + ylab("Difference from Equilibrium Offer") +
  scale_y_continuous(breaks = seq(from = -70,to = 50,by = 10)) +  
  scale_x_continuous(breaks = seq(from  =  1, to  =  8, by  =  1)) +  
  scale_shape_manual(name = "Treatment",values  =  shape.values[names(shape.values) %in% endog_endow])  +  
  scale_linetype_manual(name="Treatment",values = line.values[names(line.values) %in% endog_endow]) +
  guides(shape  =  guide_legend(nrow  =  2)) +
  theme(legend.position = "bottom", 
        legend.text = element_text(size = 12), 
        axis.title = element_text(size = 12), 
        plot.title = element_text(size = 16)) +
  coord_cartesian(ylim  =  c(-70,50)) + 
  theme_bw(base_size = 14) +
  scale_colour_manual(guide  =  "none", values  =  c("black", "gray69"))  +  
  scale_size_manual(guide  =  "none", values   =   c(2, 3.5)) +
  theme(axis.title.y  =  element_text(size  =  rel(1.2))) + 
  theme(axis.title.x  =  element_text(size  =  rel(1.2))) + 
  #theme(plot.title  =  element_text(size  =  rel(1.75))) + 
  theme(legend.text  =  element_text(size  =  rel(1)),
        legend.title  =  element_text(size  =  rel(1)),
        strip.text = element_text(size = rel(1))) + 
  facet_wrap(~Player, scales  =  'free_x') + 
  theme(legend.position = "bottom", panel.spacing = unit(2, "lines")) 


ggdraw(fig.mean.plot.diff.by.round.vulnerability)
#ggsave("FIG_APP_First_Offer_Diff_Eq_by_round_vulnerability.pdf",  plot = last_plot(),  device = "pdf",  width = 8, height = 6, units = "in")



ggdraw(fig.mean.plot.diff.by.round.endogenous)
#ggsave("FIG_APP_First_Offer_Diff_Eq_by_round_endogenous.pdf",  plot = last_plot(),  device = "pdf",  width = 8, height = 6, units = "in")



# FIGURE 9

combined.df.mc.dist.rs <- combined.df.maximum.cost %>% filter(treatment2 == "RS"|treatment2 == "RS-VN") %>% 
  dplyr::rename(Treatment = treatment2, Round = roundId) %>%
  mutate(receiverDecision = ifelse(receiverDecision == "ACCEPT", 1, 0)) %>%
  mutate(Cost.R = 100 - offer, Endow.R = 100, Net_EU_Diff = MaxCost.R- Cost.R) %>%
  mutate(Treatment = factor(Treatment, levels = c("RS", "RS-VN"))) %>% 
  ungroup() %>%
  mutate(Round = Round + 1) %>%
  mutate(Player = ifelse(Round%%2 == 1, "Offerer: Player A", "Offerer: Player B")) %>%
  mutate(Player_Number = ifelse(Round%%2 == 1, (Round + 1)/2, Round/2)) %>%
  select(-matchId, -Player1, -Player2, -groupmatch) %>%
  mutate(Round = ifelse(receiverDecision == 1, 2*Round - 1, 2*Round)) %>%
  mutate(Treatment = factor(Treatment, levels = c("RS", "RS-VN"))) %>%
  mutate(receiverDecision = ifelse(receiverDecision == 1, "Accept", "Reject")) %>%
  group_by(Round, Treatment, mover, Net_EU_Diff) %>% 
  dplyr::mutate(total = n()) %>%
  dplyr::mutate(num_assign = case_when(total == 1 ~ rep(0, n()), 
                                       TRUE ~ runif(n(), -1/2, 1/2))) %>%
  ungroup() %>%
  mutate(Net_EU_Diff_2 = Net_EU_Diff + num_assign,
         receiverDecision = factor(receiverDecision, levels = c("Accept", "Reject")),
         Treatment = factor(Treatment, levels = c("RS", "RS-VN")))


combined.df.mc.dist.rs.full <- rbind(combined.df.mc.dist.rs, combined.df.mc.dist) %>%  
  dplyr::select(-i1, -i2, -treatment, -mover2)



# FIGURE 9a
fig.dist.accepted.rejected.endogenous.baseline = combined.df.mc.dist.rs.full %>%
  filter(Treatment == "RS"|Treatment == "BL") %>%
  ggplot(aes(x = Round, y = Net_EU_Diff_2, 
             colour = receiverDecision,
             shape = receiverDecision)) + 
  geom_jitter(width = 0.3, size = 1.2, alpha = 0.5) +
  scale_x_continuous(breaks = seq(from = 1.6, to = 16.5, by = 2), labels = seq(from = 1, to = 8, by = 1)) + 
  xlab("Round") + ylab("Net Offer - CV") + 
  scale_y_continuous(breaks = seq(from = -100, to = 60, by = 50)) + 
  geom_hline(yintercept = 0, linetype = "dashed", size = .3) +
  facet_grid(Player ~ Treatment) + 
  labs(colour = "Receiver decision")  +  
  scale_shape_manual(name  =  "Receiver decision", values = c(16, 4)) + 
  scale_colour_grey(start = 0.1, end = 0.4) +  
  theme(legend.position="bottom", 
        legend.text=element_text(size=12), 
        axis.title=element_text(size=12), 
        plot.title=element_text(size=16)) +
  coord_cartesian(ylim = c(-105, 60)) + 
  theme_bw() +
  theme(axis.title.y = element_text(size = rel(1.3), vjust = 0.8), 
        axis.title.x = element_text(size = rel(1.3), vjust = -0.3),
        strip.text.x = element_text(size = rel(1.3)), 
        strip.text.y = element_text(size = rel(1.3)),
        plot.title = element_text(size = 16),  
        legend.text = element_text(size = rel(1), face = "plain"), 
        legend.title = element_text(size = rel(1), face = "plain"),
        axis.line = element_line(color = 'black'), 
        legend.background = element_blank(),  
        legend.key = element_blank(),  
        panel.background = element_blank(),  
        panel.border = element_blank(), 
        panel.grid = element_blank(), 
        plot.background = element_blank(), 
        legend.position="bottom", 
        #strip.background = element_blank()
  ) +  guides(colour = guide_legend(override.aes = list(size=2, alpha = 1))) 





fig.dist.accepted.rejected.vulnerability = combined.df.mc.dist.rs.full %>%
  filter(Treatment == "RS-VN"|Treatment == "VN") %>%
  ggplot(aes(x = Round, y = Net_EU_Diff_2, 
             colour = receiverDecision,
             shape = receiverDecision)) + 
  geom_jitter(width = 0.3, size = 1.2, alpha = 0.5) +
  scale_x_continuous(breaks = seq(from = 1.6, to = 16.5, by = 2), labels = seq(from = 1, to = 8, by = 1)) + 
  xlab("Round") + ylab("Net Offer - CV") + 
  scale_y_continuous(breaks = seq(from = -100, to = 60, by = 50)) + 
  geom_hline(yintercept = 0, linetype = "dashed", size = .3) +
  facet_grid(Player ~ Treatment) + 
  labs(colour = "Receiver decision")  +  
  scale_shape_manual(name  =  "Receiver decision", values = c(16, 4)) + 
  scale_colour_grey(start = 0.1, end = 0.4) +  
  theme(legend.position="bottom", 
        legend.text=element_text(size=12), 
        axis.title=element_text(size=12), 
        plot.title=element_text(size=16)) +
  coord_cartesian(ylim = c(-105, 60)) + 
  theme_bw() +
  theme(axis.title.y = element_text(size = rel(1.3), vjust = 0.8), 
        axis.title.x = element_text(size = rel(1.3), vjust = -0.3),
        strip.text.x = element_text(size = rel(1.3)), 
        strip.text.y = element_text(size = rel(1.3)),
        plot.title = element_text(size = 16),  
        legend.text = element_text(size = rel(1), face = "plain"), 
        legend.title = element_text(size = rel(1), face = "plain"),
        axis.line = element_line(color = 'black'), 
        legend.background = element_blank(),  
        legend.key = element_blank(),  
        panel.background = element_blank(),  
        panel.border = element_blank(), 
        panel.grid = element_blank(), 
        plot.background = element_blank(), 
        legend.position="bottom", 
        #strip.background = element_blank()
  ) +  guides(colour = guide_legend(override.aes = list(size=2, alpha = 1))) 



ggdraw(fig.dist.accepted.rejected.vulnerability)
# ggsave("FIG_APP_Dist_Accepted_Rejected_Vulnerability.pdf",  plot = last_plot(),  device = "pdf",  width = 8, height = 5, units = "in")



ggdraw(fig.dist.accepted.rejected.endogenous.baseline)
ggsave("FIG_APP_Dist_Accepted_Rejected_Endogenous.pdf",  plot = last_plot(),  device = "pdf",  width = 8, height = 5, units = "in")


###############################################################
# APPENDIX FIGURES (DEMOGRAPHIC)
###############################################################

# Figure 1: Gender 

GenderDistribution <- ggplot(QualitativeData, aes(x=Gender))+
  geom_histogram(stat = "count", width = 0.5) +
  ylab("Frequency of Gender")+
  xlab("Gender")+
  coord_fixed(ratio=.1)+
  theme(plot.title = element_text(lineheight=.8, size=10),
        axis.title.x=element_text(size=8),
        axis.title.y=element_text(size=8),
        axis.text.x=element_text(size=8),
        strip.text = element_text(size=6)) + 
  facet_wrap(~Treatment) + theme_bw()

ggdraw(GenderDistribution)
ggsave("Figure1_App",  plot = last_plot(),  device = "pdf",  width = 7, height = 7, units = "in")



# Figure 2: Age

AgeDistribution <- QualitativeData %>% filter(!(Age > 30)) %>%
  ggplot(aes(x = Age)) +
  geom_histogram(stat = "count", width = 0.5) + 
  ylab("Frequency of Age") +
  xlab("Age")+ coord_fixed(ratio=.3) +
  theme(plot.title = element_text(lineheight=.8, size=10),
        axis.title.x=element_text(size=8),
        axis.title.y=element_text(size=8),
        axis.text.x=element_text(size=8))+
  facet_wrap(~Treatment) +
  theme_bw()



ggdraw(AgeDistribution)
ggsave("Figure2_App",  plot = last_plot(),  device = "pdf",  width = 10, height = 5, units = "in")

# Figure 3: Political Party

PoliticalParty <- ggplot(QualitativeData, aes(x=Party))+
  geom_histogram(stat = "Count", width = 0.5) +
  ylab("Frequency of Party ID")+
  xlab("Party ID")+
  coord_fixed(ratio=.1)+
  theme(plot.title = element_text(lineheight=.8, size=10),
        axis.title.x=element_text(size=8),
        axis.title.y=element_text(size=8),
        axis.text.x=element_text(size=8),
        strip.text = element_text(size=8))+
  facet_wrap(~Treatment) +
  theme_bw()

ggdraw(PoliticalParty)
ggsave("Figure3_App.pdf",  plot = last_plot(),  device = "pdf",  width = 10, height = 5, units = "in")


# Figure 4: global warming opinion distribution

GlobalWarmingOpinion <- QualitativeData %>% filter(!is.na(GlobalWarmingRank)) %>% 
  ggplot(aes(x=GlobalWarmingRank)) + geom_histogram(stat = "count", width = 0.5) +
  ylab("Frequency") +
  xlab("Global Warming is a... thing \n (1 'Very Bad' to 6 ' Very Good')")+
  coord_fixed(ratio=.1) +
  theme(plot.title = element_text(lineheight=.8, size=10),
        axis.title.x=element_text(size=8),
        axis.title.y=element_text(size=8),
        axis.text.x=element_text(size=8),
        strip.text = element_text(size=8)) + 
  facet_wrap(~Treatment) + theme_bw()

ggsave("Figure4_App.pdf",  plot = last_plot(),  device = "pdf",  width = 10, height = 5, units = "in")

# Figure 5: evidence of global warming

GlobalWarmingEvidence <- QualitativeData %>% ggplot(aes(x = CloserToView))+
  geom_histogram(stat = "count", width = 0.5) + ylab("Frequency") + xlab("View on Global Warming") +
  coord_fixed(ratio=.1) +
  scale_x_discrete(breaks = c(1,2,3,4),limits=c(1:4),labels=c("Most scientists think \n global warming is happening",
                                                              "Most scientists think \n global warming is not happening",
                                                              "There is disagreement \n amongst scientists",
                                                              "I don't know \n enough to say")) + 
  theme_bw() + 
  theme(axis.title.x=element_text(size = 10),
        axis.title.y=element_text(size = 10), strip.text = element_text(size = 10),
        axis.text.x=element_text(size=8, angle=60, hjust=1)) +
  facet_wrap(~Treatment) 
ggdraw(GlobalWarmingEvidence)
ggsave("Figure5_App.pdf",  plot = last_plot(),  device = "pdf")

